<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroup_id">
        <el-select
          v-model="queryParams.edgroup_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeEdgroup(queryParams.edgroup_id, 'query')"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="学校名称"
        prop="school_id"
        v-if="queryParams.edgroup_id"
      >
        <el-select
          v-model="queryParams.school_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeSchool(queryParams.school_id, 'query')"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="班级名称"
        prop="class_id"
        v-if="queryParams.school_id"
      >
        <el-select
          v-model="queryParams.class_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
        >
          <el-option
            v-for="item in classList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学生名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="icon-search"
          clearable
          placeholder="请输入学生名称"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item label="固件版本" prop="version">
        <el-input
          v-model="queryParams.version"
          class="icon-search"
          clearable
          placeholder="请输入固件版本"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          >导入</el-button
        >
      </el-col> -->
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="creatOTA"
          v-hasPermi="['system:post:add']"
          >创建OTA任务</el-button
        >
      </el-col>-->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="studentList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
      <el-table-column
        label="学生学号"
        show-overflow-tooltip
        align="center"
        prop="s_number"
      />
      <el-table-column label="学生编号" align="center" prop="id" />
      <el-table-column
        label="学生名称"
        show-overflow-tooltip
        align="center"
        prop="name"
      >
        <template #default="scope">
          <span v-if="scope.row?.name.length">
            {{ scope.row?.name.length > 2 ? scope.row?.name[0] + '*' +scope.row?.name.slice(-1) : scope.row?.name[0] + '*' }}
          </span>
          <span v-else>暂无姓名</span>
        </template>
      </el-table-column>
      <!-- show-overflow-tooltip -->
      <el-table-column
        label="教育集团名称 / 学校名称 / 班级名称"
        width="330"
        align="center"
        prop="class.school.edgroup.name"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.class?.school?.edgroup?.name" type="error">
            {{ scope.row?.class?.school?.edgroup?.name }}
          </el-tag>
          &nbsp;
          <el-tag v-if="scope.row?.class?.school?.name" type="primary">
            {{ scope.row?.class?.school?.name }}
          </el-tag>
          &nbsp;
          <el-tag v-if="scope.row?.class?.name" type="warning">
            {{ scope.row?.class?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="学校名称"
        show-overflow-tooltip
        align="center"
        prop="class.school.name"
      />
      <el-table-column
        label="班级名称"
        show-overflow-tooltip
        align="center"
        prop="class.name"
      /> -->
      
      <el-table-column
        label="关联手环"
        show-overflow-tooltip
        align="center"
        prop="student_wristband.mac"
      />
      <el-table-column
        label="手环版本号"
        show-overflow-tooltip
        align="center"
        prop="student_wristband.wristband.fw_version"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.student_wristband?.wristband?.fw_version" type="danger">
            {{ scope.row?.student_wristband?.wristband?.fw_version }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column
        label="图片"
        show-overflow-tooltip
        align="center"
        prop="photo"
      >
        <template #default="scope">
          <div style="z-index: 10000">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.photo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
              :preview-src-list="srcList"
              show-progress
              :initial-index="0"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        fixed="right"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="StudentRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="教育集团名称" prop="class.school.edgroup.id">
          <el-select
            v-model="form.class.school.edgroup.id"
            placeholder="请选择教育集团"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
            @change="changeEdgroup(form.class.school.edgroup.id, 'edit')"
          >
            <el-option
              v-for="edgroup in EdgroupList"
              :key="edgroup.value"
              :label="edgroup.label"
              :value="edgroup.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校名称" prop="class.school.id">
          <el-select
            v-if="
              EdgroupList.length > 0 && schoolList.length > 0 && type == 'edit'
            "
            v-model="form.class.school.id"
            placeholder="请选择学校"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
            @change="changeSchool(form.class.school.id, 'edit')"
          >
            <el-option
              v-for="item in schoolList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            style="width: 260px"
            v-else
            disabled
            placeholder="该集团暂无学校"
          />
        </el-form-item>
        <el-form-item label="班级名称" prop="class.id">
          <el-select
            v-if="
              schoolList.length > 0 && classList.length > 0 && type == 'edit'
            "
            v-model="form.class.id"
            placeholder="请选择班级"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
          >
            <el-option
              v-for="item in classList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            style="width: 260px"
            v-else
            disabled
            placeholder="该学校暂无班级"
          />
        </el-form-item>
        <el-form-item label="学生名称" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入学生名称"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <el-form-item label="学生学号" prop="s_number">
          <el-input
            v-model="form.s_number"
            class="icon-search"
            clearable
            placeholder="请输入学生学号"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="limit"
            list-type="picture-card"
            v-model="form.photo"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 学生导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
  </div>
</template>

<script setup name="Ota">
import { getFirmwaresList } from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import { mqttOtaUpgrade } from "@/api/system/firmware/ota";
import {
  getStudentList,
  getStudentById,
  updateStudentById,
  createStudent,
  deleteStudentById,
} from "@/api/system/school/student";
import { getToken } from "@/utils/auth";
import { getClassList } from "@/api/system/school/class";
import { getSchoolList } from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import { version } from "nprogress";
const { proxy } = getCurrentInstance();
const limit = ref(1);
const { action_ota, firmware_type } = proxy.useDict(
  "action_ota",
  "firmware_type"
);
// const srcList = ref([]);
/*** 学生导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/student/importData"
});
const type = ref("query");
const options = reactive({
  file: null, // 上传的固件文件
  filename: "firmware", // 默认文件名称
  outputType: "bin", // 默认输出文件类型（例如 .bin 或 .hex）
  previews: {}, // 预览数据（如果需要）
});

/** 覆盖默认上传行为 */
function requestUpload() {}
const EdgroupList = ref();
const classList = ref();

/** 导入按钮操作 */
function handleImport() {
  upload.title = "学生导入";
  upload.open = true;
};
// 切换教育集团
function changeEdgroup(e, val) {
  type.value = val;
  // console.log("type_edgrp", type.value);
  if (val == "query") {
    queryParams.value.school_id = null;
  }
  if (val == "edit") {
    form.value.class.school.edgroup.name = EdgroupList.value.find(
      (item) => item.value == e
    ).label;
    form.value.class.school.edgroup.photo = EdgroupList.value.find(
      (item) => item.value == e
    ).photo;
    form.value.class.school.id = null;
    form.value.class.school.name = undefined;
    form.value.class.school.photo = undefined;
    // form.value.class.school.s_number = undefined;
  }
  schoolList.value = [];
  let params = {
    id: e,
  };
  getSchoolList(params).then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
// 切换学校
function changeSchool(e, val) {
  type.value = val;
  // console.log("type_school", type.value);
  if (val == "query") {
    queryParams.value.class_id = null;
  }
  if (val == "edit") {
    // console.log(111, form.value.class.school.id);
    // console.log(e);
    // console.log(classList.value);
    form.value.class.school.name = schoolList.value.find(
      (item) => item.value == e
    ).label;
    form.value.class.school.photo = schoolList.value.find(
      (item) => item.value == e
    ).photo;
    form.value.class.id = null;
    form.value.class.name = undefined;
    form.value.class.photo = undefined;
  }
  classList.value = [];
  let params = {
    school_id: e,
  };
  // console.log('params', params)
  getClassList(params).then((res) => {
    // console.log("班级列表", res.data.data);
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("/student/importTemplate", {
  }, `student_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 上传预处理 */
function beforeUpload(file) {
  // 定义允许的固件文件格式
  const allowedFirmwareTypes = [".bin", ".hex"];
  const fileExtension = file.name
    .slice(file.name.lastIndexOf("."))
    .toLowerCase();

  // 校验文件格式
  if (!allowedFirmwareTypes.includes(fileExtension)) {
    proxy.$modal.msgError(
      "文件格式错误，请上传固件类型文件，如：.bin 或 .hex 后缀的文件。"
    );
    return false; // 阻止上传
  }

  // 校验文件大小（例如限制为 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$modal.msgError("文件大小超过限制，请上传小于 10MB 的文件。");
    return false; // 阻止上传
  }
  // 文件格式和大小都符合要求
  options.file = file; // 存储文件对象
  options.filename = file.name; // 存储文件名
  form.value.name = file.name;
  return true;
}
// console.log(firmware_type);
const schoolList = ref([]);
const studentList = ref([]);
const firmwaresLists = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    version: undefined,
  },
  rules: {
    "class.school.edgroup.id": [
      { required: true, message: "教育集团名称不能为空", trigger: "blur" },
    ],
    "class.school.id": [
      { required: true, message: "学校名称不能为空", trigger: "blur" },
    ],
    "class.id": [
      { required: true, message: "班级名称不能为空", trigger: "blur" },
    ],
    name: [{ required: true, message: "学生名称不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
function rawChange(val) {
  if (!val) {
  }
}

/** 查询学生列表 */
function getList() {
  loading.value = true;
  classList.value = [];
  // srcList.value = [];
  // console.log('queryParams.value', queryParams.value)
  getStudentList(queryParams.value).then((response) => {
    console.log("学生列表", response.data.data);
    studentList.value = response.data.data;
    // studentList.value.forEach((item) => {
    //   srcList.value.push(item.photo);
    // });
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  type.value = "edit";
  const id = row.id || ids.value;
  // console.log("id", id);
  schoolList.value = [];
  classList.value = [];
  getStudentById(id).then((response) => {
    console.log(response.data);
    form.value = response.data;
    let params = {
      id: form.value.class.school.edgroup.id,
    };
    // console.log(params);
    // 学校列表
    getSchoolList(params).then((res) => {
      schoolList.value = res.data.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          photo: item.photo,
        };
      });
    });
    // console.log("schoolList 完成");
    let classParams = {
      school_id: form.value.class.school.id,
    };
    console.log(classParams);
    // 班级列表
    getClassList(classParams).then((res) => {
      // console.log('班级列表', res.data.data)
      classList.value = res.data.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          photo: item.photo,
        };
      });
    });
    // console.log("classList 完成");
    open.value = true;
    title.value = "修改学生";
  });
}

// 固件列表
function getFirmwaresLists() {
  getFirmwaresList().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      firmwaresLists.value = data;
    } else {
      firmwaresLists.value = [];
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    name: "", //
    s_number: "", // 学号
    // photo: "",
    class: {
      id: null,
      name: undefined,
      photo: undefined,
      school: {
        id: null,
        name: undefined,
        photo: undefined,
        edgroup: {
          id: null,
          name: undefined,
          photo: undefined,
        },
      },
    },
  };
  proxy.resetForm("StudentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // console.log('form.value', form.value )
  open.value = true;
  title.value = "新增学生";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["StudentRef"].validate((valid) => {
    if (valid) {
      console.log(111, form.value.id);
      form.value.class.name = classList.value.find(
        (item) => item.value == form.value.class.id
      ).label;
      form.value.class.photo = classList.value.find(
        (item) => item.value == form.value.class.id
      ).photo;
      if (form.value.id != undefined) {
        console.log(form.value);
        updateStudentById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("修改失败");
          }
        });
      } else {
        // console.log("add", form.value);
        createStudent(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("新增失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteStudentById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 修改操作 */
function handleEdit(row) {
  const params = {
    taskId: row.id,
    schoolid: row.schoolid,
    localPath: row.path,
    force: row.force || false,
  };
  proxy.$modal
    .confirm(`是否现在升级任务编号为 ${row.id} 的任务？`)
    .then(function () {
      return mqttOtaUpgrade(params);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("开始升级");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}
function initData(){
  getEdgroupList().then((res) => {
    EdgroupList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getSchoolList().then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getClassList().then((res) => {
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getFirmwaresLists();
  getList();
}
initData();
</script>

<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
